<template>
  <m-modal v-model="visible" title="选择元素类型" @ok="handleOk" @cancel="handleCancel">
    <m-attr-tip type="relationType" />
    <div style="padding: 10px 22px 0 22px">
      <a-select
        show-search
        placeholder="搜索"
        option-filter-prop="children"
        style="width: 100%;"
        size="small"
        @change="handleSelectChange"
        @search="handleSelectSearch"
      >
        <a-icon slot="suffixIcon" type="search" />
        <a-select-option v-for="(item,index) in selectOptions" :key="index"  :value="item.id" :title="item.label">
          {{item.label}}
        </a-select-option>
      </a-select>
    </div>
    
    <a-tabs v-model="selectInfo.curTab" type="card" class="_tab">
      <a-tab-pane key="tree" tab="树" style="overflow-y:auto;border: 1px solid #D9D9D9;">
        <div class="g-pd-20 element-tree" style="height:400px;">
          <a-tree
            :default-checked-keys="defaultChecks"
            :defaultExpandAll="true"
            :draggable="false"
            :show-line="true"
            :checkable="true"
            :treeData="treeData"
            @check="onCheck"
          >

            <template  slot-scope="scope" >
              <span :id="'v'+scope.key">
                <img  :src="scope.icon" alt="req"/>
                <span class="g-m-l-4">{{scope.title|| '---'}}</span>
              </span>
            </template>
          </a-tree>
        </div>
      </a-tab-pane>
      <a-tab-pane key="list" tab="列表" style="overflow-y:auto;border: 1px solid #D9D9D9;">
        <div class="g-pd-20 element-list" style="height:400px;">
          <a-checkbox-group
            :options="list"
            style="display:flex;flex-direction:column"
            @change="handleListSelect"
          >

            <template slot="label"  slot-scope="scope" >
              <span :id="'v'+scope.key">
                <img  :src="scope.icon" alt="req"/>
                {{scope.title|| '---'}}
              </span>
            </template>

          </a-checkbox-group>

        </div>
      </a-tab-pane>
    </a-tabs>
  </m-modal>
</template>
<script>
import { Portal } from 'src/components/common/Portal.vue';
import { treeForEach, findNodeByValue } from 'src/util/common';
import Modal from 'src/components/common/CustomModal';
import AttrTip from 'src/components/Attribute/comps/AttrTip';
import { debounce } from 'lodash';
import treeUtil from 'src/components/ModelTree/treeUtil';
//// this.$emit('check', checkedObj, eventObj);
const treeDataDefault = [
  {
    title: '<<抽象的需求类型>>',
    key: '0-0',
    value: '0',
    disabled: true,
    disableCheckbox: true,
    icon: "statics/images/sysml/Requirement.svg",
    scopedSlots: {
      title: "default"

    },
    children: [
      {
        title: '需求',
        key: '0-0-0',
        value: '1',
        icon: "statics/images/sysml/Requirement.svg",
        scopedSlots: {
          title: "default"

        },
      },
      {
        title: '拓展需求',
        key: '0-0-1',
        value: '2',
        icon: "statics/images/sysml/Requirement.svg",
        scopedSlots: {
          title: "default"

        },
        //// children: [{ key: '0-0-1-0', slots: { title: 'title0010' } }],
      },
      {
        title: '商务需求',
        key: '0-0-2',
        value: '3',
        icon: "statics/images/sysml/Requirement.svg",
        scopedSlots: {
          title: "default"

        },
        //// children: [{ key: '0-0-1-0', slots: { title: 'title0010' } }],
      }
    ],
  }
];
const comp = {
  name: 'comp-select-value',
  components: {
    'm-modal': Modal,
    'm-attr-tip': AttrTip,

  },
  props: {
    defaultChecks: Array,
    propertyKey: String,
    selectedElement: Object,
    graphType: {
      type: String,
      default: 'graph'
    },

  },
  data() {
    let selectedItem;
    let treeList;
    let checkedIds = [];
    if (this.graphType === 'matrix' ){
      treeList = treeUtil.buildMatrixTypeList();
    } else if (this.graphType === 'traceDiagram'){
      treeList = this.buildTraceDiagram();
    }
    checkedIds = this.defaultChecks;
    if (this.currentId){
      selectedItem = findNodeByValue(treeList, this.currentId);
    }

    return {
      visible: false,
      treeData: treeList,
      checkedIds: checkedIds,
      selectInfo: {
        treeSelectItem: selectedItem,
        listSelectItem: selectedItem,
        curTab: 'tree'
      },
      selectOptions: [],
      checkedValues: [],
      selectOptionsCache: []
    };
  },
  mounted() {
    this.visible = true;
  },
  computed: {
    list(){ return this.getList(); }
  },
  methods: {
    buildTraceDiagram(){
      return [
        {
          title: '<<抽象的需求类型>>',
          key: '0-0',
          value: '0',
          disabled: true,
          disableCheckbox: true,
          icon: "statics/images/sysml/Requirement.svg",
          scopedSlots: {
            title: "default"

          },
          children: [
            {
              title: '需求',
              key: '0-0-0',
              value: '1',
              icon: "statics/images/sysml/Requirement.svg",
              scopedSlots: {
                title: "default"

              },
            },
            {
              title: '拓展需求',
              key: '0-0-1',
              value: '2',
              icon: "statics/images/sysml/Requirement.svg",
              scopedSlots: {
                title: "default"

              },
              //// children: [{ key: '0-0-1-0', slots: { title: 'title0010' } }],
            },
            {
              title: '商务需求',
              key: '0-0-2',
              value: '3',
              icon: "statics/images/sysml/Requirement.svg",
              scopedSlots: {
                title: "default"

              },
              //// children: [{ key: '0-0-1-0', slots: { title: 'title0010' } }],
            }
          ],
        }
      ];
    },
    handleCancel(){
      this.visible = false;
      this.$emit('close');
    },
    getList(){
      const list = [];
      treeForEach(this.treeData, node => {
        list.push(node);
      });
      return list;

    },

    onCheck(checkedKeys, info) {
      this.checkedIds = checkedKeys;
      //// this.checkedValues = info.checkedNodes.map(node => node.data.props.value);
      //// console.log('onCheck', checkedKeys, info, this.checkedIds, this.treeData, this.checkedValues);
    },
    handleOk(){
      this.visible = false;
      let checkedNodes = this.treeData[0].children.filter((item) => {
        return this.checkedIds.includes(item.key);
      });
      //// 第一级选中
      if (this.graphType === 'matrix' ){
        this.treeData.filter(x => this.checkedIds.includes(x.key)).forEach(x => checkedNodes.push(x)); }
      console.log({ checkedNodes }, this.checkedIds);
      this.$emit('sure', { checkedNodes });
    },
    handleListSelect(models){
      //// this.checkedValues = models;
      this.selectInfo.listSelectItems = models;

    },
    getSelectedItem(){
      return this.selectInfo.curTab === 'tree' ? this.selectInfo.treeSelectItems : this.selectInfo.listSelectItems;

    },
    insertRight(items){
      items.forEach(item => {
        if (!this.selectInfo.rightSelects.find(i => i.key === item.key)){
          this.selectInfo.rightSelects.push(item);
          item.disabled = true;
        }

      });

    },

    handleFresh(){
      this.selectInfo.rightSelects = [];

    },
    handleRemove(item){
      this.selectInfo.rightSelects = this.selectInfo.rightSelects.filter(i => i !== item);
      item.disabled = false;
    },
    
    handleSelectSearch: debounce(function(query){
      console.log(query);
      const flatData = [];
      if (query === '' ) {
        this.selectOptions = [];
        return flatData;
      };
      query = query.toLowerCase();
      treeForEach(this.treeData, i => {
        
        if ( i.title.toLowerCase().includes(query) ) {

          flatData.push({ label: i.title, id: i.key });
        };
      });
      this.selectOptions = flatData;

    }, 200),
    handleSelectChange(id){
      console.log(id);
      const result = this.list.find(it => it.key === id);
      console.log('this.selectOptionsCache', this.selectOptionsCache);
      this.selectOptionsCache.forEach(id => {
        this.list.find(it => it.key === id).selected = false;
      });
      this.selectOptionsCache = [];
      this.selectOptionsCache.push(id);
      this.onCheck(this.selectOptionsCache);
      //// this.handleTreeSelect(result, true);
      //// result.selected = true;
      //// this.expandParent(result);
      /*
       handleCheck(checkedObj: (number | string)[], eventObj: CheckEvent) {
      this.$emit('update:checkedKeys', checkedObj);
      this.$emit('check', checkedObj, eventObj);
    },
      */
      //// this.$emit('update:checkedKeys', this.selectOptionsCache);

      this.$nextTick(() => {
        let wrapperClass =  this.selectInfo.curTab === 'tree' ? '.element-tree' : '.element-list';
       
        const dom = document.querySelector(wrapperClass + ' #v' + result.key); 
        if (dom){
          dom.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
        }
      });

    },
    expandParent(node){
      if (node.parent){
        node.parent.expand = true;
        this.expandParent(node.parent);
      }

    }
    
  }
};
export default comp;
export const elementTypeModal = new Portal(comp);
</script>
<style lang="scss" scoped>
._tab {
  padding-left: 22px;
  padding-right: 22px;
  padding-top: 17px;
}
.ant-tree.ant-tree-show-line li:not(:last-child)::before {
    position: absolute;
    left: 12px;
    width: 1px;
    height: calc(100% - 22px);
    margin: 22px 0 0;
    border-left: 1px solid #d9d9d9;
    content: ' ';
}
.ant-tree-show-line li::before {
    border-left: 1px rgba(0, 0, 0, 0.45) dashed !important;
    height: calc(100% - 0px) !important;
    top: 11px;
    margin: 0 !important;
}
.element-tree{

}
.element-list{

}

.v-select-list {
	._row {
		cursor: pointer;
		&:hover {
			background-color: #e6f7ff;
		}
		&._selected {
				background-color:#bae7ff;
				&:hover {
					background-color: #bae7ff;
				}
		}
    &._disabled {
      background: white;
      color: rgba(0,0,0,0.25);
      cursor:not-allowed
    }

	}

}
</style>
